package com.gan.bi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Scanner;

public class TopicProducer {

  private static final String EXCHANGE_NAME = "topic_exchange";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try (Connection connection = factory.newConnection();
         Channel channel = connection.createChannel()) {

        // 声明并绑定路由交换机和对应的队列以及它们的路由键
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        channel.queueDeclare("xw", true, false, false, null);
        channel.queueBind("xw", EXCHANGE_NAME, "#.xiaowang.#");
        channel.queueDeclare("xg", true, false, false, null);
        channel.queueBind("xg", EXCHANGE_NAME, "#.xiaogan.#");
        channel.queueDeclare("xh", true, false, false, null);
        channel.queueBind("xh", EXCHANGE_NAME, "#.xiaohong.#");

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String userInput = sc.nextLine();
            String[] inputs = userInput.split(" ");
            if (inputs.length != 2){
                continue;
            }
            // 拿到消息和路由键后往交换机上发消息
            String message = inputs[0];
            String topicKey = inputs[1];
            channel.basicPublish(EXCHANGE_NAME,topicKey, null, message.getBytes("UTF-8"));
            System.out.println("Sent '" + message + "' to  " + topicKey);
    }
  }
}
}